<template>
  <div class="min-h-screen bg-base-200 flex">
    <!-- 左侧边栏 -->
    <div id="sidebar" class="sidebar sidebar-expanded bg-base-100 shadow-xl border-r border-base-300 flex flex-col transition-all duration-400">
      <!-- 应用标题 -->
      <div class="p-6 border-b border-base-300">
        <div class="flex items-center justify-between">
          <div class="flex items-center space-x-3 fade-text">
            <div class="w-10 h-10 rounded-xl bg-gradient-to-br from-indigo-500 to-purple-600 flex items-center justify-center shadow-lg">
              <i class="fas fa-brain text-white text-lg"></i>
            </div>
            <div>
              <h1 class="font-bold text-xl bg-gradient-to-r from-indigo-600 to-purple-600 bg-clip-text text-transparent">博沃智慧</h1>
              <p class="text-xs text-base-content/70">MCP管理</p>
            </div>
          </div>
          <button id="sidebarToggle" class="btn btn-ghost btn-sm">
            <i class="fas fa-bars text-base-content"></i>
            <i class="fas fa-chevron-left text-base-content hidden"></i>
          </button>
        </div>
      </div>

      <!-- 导航菜单 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar p-4">
        <nav class="space-y-2">
          <router-link to="/chat" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-base-200 transition-colors fade-text">
            <i class="fas fa-comments text-base-content/70"></i>
            <span class="text-base-content">对话界面</span>
          </router-link>
          <router-link to="/settings" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-base-200 transition-colors fade-text">
            <i class="fas fa-cog text-base-content/70"></i>
            <span class="text-base-content">系统设置</span>
          </router-link>
          <router-link to="/knowledge" class="flex items-center space-x-3 p-3 rounded-lg hover:bg-base-200 transition-colors fade-text">
            <i class="fas fa-book text-base-content/70"></i>
            <span class="text-base-content">知识库管理</span>
          </router-link>
          <router-link to="/mcp-management" class="flex items-center space-x-3 p-3 rounded-lg bg-primary/10 text-primary border border-primary/20 fade-text">
            <i class="fas fa-plug text-primary"></i>
            <span class="font-medium">MCP管理</span>
          </router-link>
        </nav>
      </div>

      <!-- 用户信息 -->
      <div class="p-4 border-t border-base-300">
        <div class="flex items-center space-x-3">
          <div class="avatar">
            <div class="w-12 h-12 rounded-full bg-gradient-to-br from-emerald-400 to-cyan-500 flex items-center justify-center shadow-lg">
              <span class="text-white text-lg font-bold">{{ authStore.username?.charAt(0).toUpperCase() }}</span>
            </div>
          </div>
          <div class="fade-text flex-1">
            <p class="font-semibold text-base-content">{{ authStore.username }}</p>
            <p class="text-xs text-base-content/70">专业版用户</p>
          </div>
          <div class="fade-text">
            <router-link to="/chat" class="btn btn-ghost btn-sm">
              <i class="fas fa-sign-out-alt text-base-content/70"></i>
            </router-link>
          </div>
        </div>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="flex-1 flex flex-col bg-base-100">
      <!-- 标题栏 -->
      <div class="bg-base-100 border-b border-base-300 p-6">
        <div class="flex items-center justify-between">
          <div>
            <h1 class="text-2xl font-bold text-base-content">MCP服务管理</h1>
            <p class="text-base-content/70 mt-1">管理和配置您的Model Context Provider服务</p>
          </div>
          <button
            @click="showCreateModal = true"
            class="btn btn-primary"
          >
            <i class="fas fa-plus mr-2"></i>创建MCP服务
          </button>
        </div>
      </div>

      <!-- 内容区域 -->
      <div class="flex-1 overflow-y-auto custom-scrollbar p-6">
        <!-- 错误提示 -->
        <div v-if="mcpStore.error" class="alert alert-error mb-6">
          <svg xmlns="http://www.w3.org/2000/svg" class="stroke-current shrink-0 h-6 w-6" fill="none" viewBox="0 0 24 24">
            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M10 14l2-2m0 0l2-2m-2 2l-2-2m2 2l2 2m7-2a9 9 0 11-18 0 9 9 0 0118 0z" />
          </svg>
          <span>{{ mcpStore.error }}</span>
        </div>

        <!-- MCP服务列表 -->
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          <div
            v-for="service in mcpStore.mcpServices"
            :key="service.id"
            class="card bg-base-100 shadow-sm border border-base-300 hover:shadow-md transition-shadow"
          >
            <div class="card-body">
              <div class="flex items-start justify-between mb-4">
                <div class="flex items-center">
                  <div class="w-12 h-12 rounded-lg bg-secondary/10 flex items-center justify-center mr-3">
                    <i class="fas fa-plug text-secondary text-xl"></i>
                  </div>
                  <div>
                    <h3 class="font-semibold text-base-content">{{ service.name }}</h3>
                    <span :class="['badge badge-sm', service.is_active ? 'badge-success' : 'badge-warning']">
                      {{ service.is_active ? '运行中' : '已停止' }}
                    </span>
                  </div>
                </div>
                <div class="dropdown dropdown-end">
                  <div tabindex="0" role="button" class="btn btn-ghost btn-sm">
                    <i class="fas fa-ellipsis-v"></i>
                  </div>
                  <ul class="dropdown-content menu p-2 shadow-xl bg-base-100 rounded-box w-32 z-[1]">
                    <li><a @click="editMcpService(service)" class="text-secondary"><i class="fas fa-edit mr-2"></i>编辑</a></li>
                    <li><a @click="testConnection(service)" class="text-info"><i class="fas fa-wifi mr-2"></i>测试</a></li>
                    <li><a @click="deleteMcpService(service.id)" class="text-error"><i class="fas fa-trash mr-2"></i>删除</a></li>
                  </ul>
                </div>
              </div>
              
              <p class="text-base-content/70 text-sm mb-3">{{ service.description }}</p>
              
              <div class="bg-base-200 rounded-lg p-3 mb-3">
                <p class="text-xs text-base-content/50 mb-1">服务器地址</p>
                <p class="text-sm font-mono text-base-content break-all">{{ service.server_url }}</p>
              </div>
              
              <div class="flex justify-between items-center text-xs text-base-content/50">
                <span>创建: {{ formatDate(service.created_at) }}</span>
                <span>更新: {{ formatDate(service.updated_at) }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 空状态 -->
        <div v-if="mcpStore.mcpServices.length === 0 && !mcpStore.isLoading" class="text-center py-12">
          <div class="mx-auto w-16 h-16 rounded-full bg-base-200 flex items-center justify-center mb-4">
            <i class="fas fa-plug text-2xl text-base-content/30"></i>
          </div>
          <h3 class="text-lg font-medium text-base-content mb-2">暂无MCP服务</h3>
          <p class="text-base-content/70 mb-4">创建您的第一个MCP服务开始使用</p>
          <button
            @click="showCreateModal = true"
            class="btn btn-primary"
          >
            <i class="fas fa-plus mr-2"></i>创建MCP服务
          </button>
        </div>

        <!-- 加载状态 -->
        <div v-if="mcpStore.isLoading" class="text-center py-12">
          <span class="loading loading-spinner loading-lg text-secondary"></span>
          <p class="mt-2 text-base-content/70">加载中...</p>
        </div>
      </div>
    </div>

    <!-- 创建/编辑模态框 -->
    <div v-if="showCreateModal || showEditModal" class="modal modal-open">
      <div class="modal-box max-w-md">
        <h3 class="font-bold text-lg mb-4">
          {{ showEditModal ? '编辑MCP服务' : '创建MCP服务' }}
        </h3>
        
        <form @submit.prevent="handleSubmit" class="space-y-4">
          <div class="form-control">
            <label class="label">
              <span class="label-text">服务名称</span>
            </label>
            <input
              v-model="formData.name"
              type="text"
              required
              class="input input-bordered"
              placeholder="请输入服务名称"
            />
          </div>
          
          <div class="form-control">
            <label class="label">
              <span class="label-text">服务描述</span>
            </label>
            <textarea
              v-model="formData.description"
              rows="3"
              required
              class="textarea textarea-bordered"
              placeholder="请输入服务描述"
            ></textarea>
          </div>
          
          <div class="form-control">
            <label class="label">
              <span class="label-text">服务器地址</span>
            </label>
            <input
              v-model="formData.server_url"
              type="url"
              required
              class="input input-bordered"
              placeholder="http://localhost:8080"
            />
          </div>
          
          <div v-if="showEditModal" class="form-control">
            <label class="label cursor-pointer">
              <input
                v-model="formData.is_active"
                type="checkbox"
                class="checkbox checkbox-secondary"
              />
              <span class="label-text">启用服务</span>
            </label>
          </div>
          
          <div class="modal-action">
            <button
              type="button"
              @click="closeModal"
              class="btn btn-ghost"
            >
              取消
            </button>
            <button
              type="submit"
              :disabled="mcpStore.isLoading"
              class="btn btn-secondary"
            >
              <span v-if="mcpStore.isLoading" class="loading loading-spinner loading-sm"></span>
              {{ mcpStore.isLoading ? '处理中...' : (showEditModal ? '更新' : '创建') }}
            </button>
          </div>
        </form>
      </div>
    </div>

    <!-- 连接测试模态框 -->
    <div v-if="showTestModal" class="modal modal-open">
      <div class="modal-box max-w-md">
        <h3 class="font-bold text-lg mb-4">连接测试</h3>
        
        <div class="space-y-4">
          <div class="flex items-center justify-between">
            <span class="text-base-content">服务名称</span>
            <span class="font-medium">{{ testingService?.name }}</span>
          </div>
          
          <div class="flex items-center justify-between">
            <span class="text-base-content">服务器地址</span>
            <span class="text-sm font-mono text-base-content/70">{{ testingService?.server_url }}</span>
          </div>
          
          <div v-if="testResult" class="alert" :class="testResult.success ? 'alert-success' : 'alert-error'">
            <i :class="testResult.success ? 'fas fa-check-circle' : 'fas fa-times-circle'"></i>
            <span>{{ testResult.message }}</span>
          </div>
          
          <div v-if="testing" class="flex items-center justify-center">
            <span class="loading loading-spinner loading-md"></span>
            <span class="ml-2 text-base-content/70">正在测试连接...</span>
          </div>
        </div>
        
        <div class="modal-action">
          <button @click="closeTestModal" class="btn" :disabled="testing">关闭</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue';
import { useMcpServiceStore } from '../stores/mcpService';
import { useAuthStore } from '../stores/auth';

const mcpStore = useMcpServiceStore();
const authStore = useAuthStore();

const showCreateModal = ref(false);
const showEditModal = ref(false);
const showTestModal = ref(false);
const editingId = ref<number | null>(null);
const sidebarCollapsed = ref(false);

const formData = reactive({
  name: '',
  description: '',
  server_url: '',
  is_active: true
});

const testingService = ref<any>(null);
const testing = ref(false);
const testResult = ref<any>(null);

onMounted(async () => {
  await mcpStore.fetchMcpServices();
});

const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleDateString('zh-CN');
};

const editMcpService = (service: any) => {
  editingId.value = service.id;
  formData.name = service.name;
  formData.description = service.description;
  formData.server_url = service.server_url;
  formData.is_active = service.is_active;
  showEditModal.value = true;
};

const testConnection = (service: any) => {
  testingService.value = service;
  testing.value = true;
  testResult.value = null;
  showTestModal.value = true;
  
  // 模拟连接测试
  setTimeout(() => {
    testing.value = false;
    testResult.value = {
      success: Math.random() > 0.3, // 70%成功率
      message: Math.random() > 0.3 
        ? '连接成功！服务器响应正常。' 
        : '连接失败：无法连接到服务器，请检查网络连接和服务器状态。'
    };
  }, 2000);
};

const deleteMcpService = async (id: number) => {
  if (confirm('确定要删除这个MCP服务吗？')) {
    await mcpStore.deleteMcpService(id);
  }
};

const handleSubmit = async () => {
  if (showEditModal.value && editingId.value) {
    await mcpStore.updateMcpService(editingId.value, formData);
  } else {
    await mcpStore.createMcpService(formData);
  }
  
  if (!mcpStore.error) {
    closeModal();
  }
};

const closeModal = () => {
  showCreateModal.value = false;
  showEditModal.value = false;
  editingId.value = null;
  formData.name = '';
  formData.description = '';
  formData.server_url = '';
  formData.is_active = true;
  mcpStore.clearError();
};

const closeTestModal = () => {
  showTestModal.value = false;
  testingService.value = null;
  testing.value = false;
  testResult.value = null;
};

// 侧边栏折叠功能
const toggleSidebar = () => {
  sidebarCollapsed.value = !sidebarCollapsed.value;
  const sidebar = document.getElementById('sidebar');
  const fadeTexts = document.querySelectorAll('.fade-text');
  const barsIcon = document.querySelector('#sidebarToggle .fa-bars');
  const chevronIcon = document.querySelector('#sidebarToggle .fa-chevron-left');
  
  if (sidebarCollapsed.value) {
    sidebar?.classList.add('sidebar-collapsed');
    sidebar?.classList.remove('sidebar-expanded');
    barsIcon?.classList.add('hidden');
    chevronIcon?.classList.remove('hidden');
  } else {
    sidebar?.classList.remove('sidebar-collapsed');
    sidebar?.classList.add('sidebar-expanded');
    barsIcon?.classList.remove('hidden');
    chevronIcon?.classList.add('hidden');
  }
  
  setTimeout(() => {
    fadeTexts.forEach((text: any) => {
      if (sidebarCollapsed.value) {
        text.classList.add('hidden');
      } else {
        text.classList.remove('hidden');
      }
    });
  }, sidebarCollapsed.value ? 0 : 200);
};

onMounted(() => {
  const sidebarToggle = document.getElementById('sidebarToggle');
  if (sidebarToggle) {
    sidebarToggle.addEventListener('click', toggleSidebar);
  }
});
</script>

<style scoped>
/* 自定义滚动条 */
.custom-scrollbar::-webkit-scrollbar {
  width: 6px;
}

.custom-scrollbar::-webkit-scrollbar-track {
  background: hsl(var(--b2));
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb {
  background: hsl(var(--bc) / 0.3);
  border-radius: 3px;
}

.custom-scrollbar::-webkit-scrollbar-thumb:hover {
  background: hsl(var(--bc) / 0.5);
}

/* 侧边栏动画 */
.sidebar {
  transition: all 0.4s cubic-bezier(0.4, 0, 0.2, 1);
}

.sidebar-collapsed {
  width: 64px !important;
}

.sidebar-expanded {
  width: 15% !important;
}

/* 文本淡入淡出 */
.fade-text {
  transition: opacity 0.3s ease-in-out;
}

.fade-text.hidden {
  opacity: 0;
  pointer-events: none;
}
</style>